<script setup lang="ts" name="ResidentArchives">
import {onActivated, ref, reactive} from 'vue'
import {FormRules} from 'element-plus'
import {HeaderData, Operation as Oper, RowOperbuttons} from '@/components/dTable/dTable'
import {OperButton, SearchButton, SearchFromItem, SearchFromJustify} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import {ColorTheme, DialogType} from '@/api/config'
import operation from '@/components/dTable/components/operation.vue'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import addArchives from './addArchives.vue'
import insert from './insert.vue'
import {downLacolFile, NoNumber, NotLeadingAndTrailingSpaces, transfDicArrData} from '@/util/common'
import {getResidentArchivesList, ResidentList} from '@/api/publicHealthExamination/residentArchives'
import {SeleteData} from '@/api/config'
import userCommon from '@/store/common'
import {HXGCReader} from '@/util/idReader'
import {getTeamListAll, SelectTeamLsit} from '@/api/publicHealthExamination/communitySettings'
const common = userCommon.setup().store
//当前页面 表格数据 定义
const tableData = ref<Array<ResidentList & RowOperbuttons>>([])

// 民族下拉
const seleteNationData = ref<Array<SeleteData>>([])

// 社区下拉
const selectTeamLsit = ref<Array<SelectTeamLsit>>([])

// 既往史下拉
const pastHistoryLsit = ref<Array<SeleteData>>([])

const IDReader = ref()

//显示加载状态
const showLoading = ref(false)

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'name',
    label: '姓名',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'portrait',
    label: '头像',
    columnType: 'slot',
    align: 'center',
    width: '80'
  },
  {
    prop: 'idNo',
    label: '身份证号',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'gender',
    label: '性别',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'age',
    label: '年龄',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'nationName',
    label: '民族',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'phone',
    label: '联系电话',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'pastHistory',
    label: '既往史',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'teamName',
    label: '社区',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'address',
    label: '居住地址',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'lastCheckupTime',
    label: '末次体检日期',
    columnType: 'text',
    'min-width': '100'
  },
  {
    prop: 'oper',
    label: '操作',
    columnType: 'slot',
    align: 'center',
    width: '65',
    fixed: 'right'
  }
])

//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {
    label: '社区',
    placeholder: '请选择社区',
    prop: 'teamId',
    type: 'selete',
    filterable: true,
    seleteData: selectTeamLsit.value
  },
  {
    label: '身份证号',
    placeholder: '请输入身份证号',
    prop: 'idNo',
    type: 'input',
    enterSubmit: true
  },
  {
    label: '姓名',
    placeholder: '请输入姓名',
    prop: 'name',
    type: 'input',
    enterSubmit: true
  },
  {
    label: '既往史',
    placeholder: '请选择既往史',
    prop: 'pastHistory',
    type: 'selete',
    filterable: true,
    seleteData: pastHistoryLsit.value
  }
])

const searchFromRules = reactive<FormRules>({
  idNo: [
    {
      message: '长度应不超过18个字符',
      max: 18,
      trigger: ['change', 'blur']
    }
  ],
  name: [
    {
      message: '长度应不超过20个字符',
      trigger: ['change', 'blur'],
      max: 20
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

const searchFromData = reactive<Partial<ResidentList>>({})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  },
  {
    label: '导入名单',
    type: 'noraml',
    elType: 'default',
    iconConfig: {icon: 'common-import', type: 'custom', color: ColorTheme},
    code: 'import',
    class: {'import-btn': true}
  },
  {
    label: '模板下载',
    type: 'link',
    code: 'templateDownload',
    class: [{'template-download-btn': true}]
  }
])

//分页配置
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

//表单靠左还是靠右
const searchFromJustify = ref<SearchFromJustify>('flexStart')

//搜索按钮配置
const searchButtons = ref<Array<SearchButton>>([{type: 'search'}, {type: 'clear'}])

//操作按钮定义
const rowOperButtons: Array<Oper> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {
      icon: 'common-edit',
      type: 'custom',
      color: ColorTheme,
      size: 20
    }
  }
]

//后端数据拼接字段事件
const setTableData = (data: Array<ResidentList>) => {
  const dataArr: Array<ResidentList & RowOperbuttons> = []
  data.forEach((item) => {
    // 删除默认日期，后端要求的
    if (item.lastCheckupTime === '1970-01-01') {
      delete item.lastCheckupTime
    }
    dataArr.push({...item, oper: rowOperButtons})
  })
  tableData.value = dataArr
}

//搜索数据事件
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.value.currentPage = 1
  getResidentArchivesList({
    ...searchFromData,
    page: pageConfig.value.currentPage,
    limit: pageConfig.value.pageSize
  })
    .then((res) => {
      showLoading.value = false
      const {data} = res.data
      pageConfig.value.total = data.total === null ? 0 : data.total
      setTableData(data.records)
    })
    .catch((error) => {
      showLoading.value = false
      console.warn(error)
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//显示新增/编辑弹窗
const showDialog = ref(false)

const showInsertDialog = ref(false)

//弹窗类型
const dialogType = ref<DialogType>('add')

//编辑的档案管理数据
const archivesData = ref<Partial<ResidentList>>({})

//操作按钮事件
const onOperation = (name: string) => {
  if (name === 'add') {
    archivesData.value = {}
    dialogType.value = 'add'
    showDialog.value = true
  } else if (name === 'import') {
    showInsertDialog.value = true
  } else if (name === 'templateDownload') {
    downLacolFile('体检系统-导入名单模板.xlsx', '/resources/体检系统-导入名单模板.xlsx')
  }
}

/**
 * @description: 新增/编辑弹窗关闭
 * @return {*}
 */
const onClose = () => {
  showDialog.value = false
  searchData()
}

/**
 * @description: 导入弹窗关闭
 * @return {*}
 */
const onInsertClose = () => {
  showInsertDialog.value = false
  searchData()
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//编辑档案管理信息事件
const editArchives = (row: ResidentList) => {
  archivesData.value = {...row}
  dialogType.value = 'edit'
  showDialog.value = true
}

//操作插槽事件（编辑，删除）事件
const cellOperation = (name: string, row: ResidentList) => {
  if (name === 'edit') {
    editArchives(row)
  }
}

/**
 * @description: 获取社区下拉
 * @return {*}
 */
const getTeamSelect = () => {
  selectTeamLsit.value.length = 0
  getTeamListAll().then((res) => {
    res.data.data?.length &&
      res.data.data.forEach((item) => {
        selectTeamLsit.value.push({label: item.name, value: item.id || '', address: `${item.regionName || ''}${item.address || ''}`})
      })
  })
}

/**
 * @description: 获取下拉字典
 * @return {*}
 */
const getDict = () => {
  seleteNationData.value.length = 0
  common.getDicData('nation').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      seleteNationData.value.push(item)
    })
  })
  // 既往史下拉
  pastHistoryLsit.value.length = 0
  common.getDicData('past_history').then((res) => {
    res &&
      res?.forEach((item) => {
        pastHistoryLsit.value.push({label: item.dictItemName, value: item.dictItemName})
      })
  })
}

onActivated(() => {
  IDReader.value = new HXGCReader()
  getTeamSelect()
  getDict()
  searchData()
})
</script>
<template>
  <page-container>
    <d-table-promote
      :label-width="70"
      :show-loading="showLoading"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :search-form-items="searchFromItems"
      :search-from-justify="searchFromJustify"
      :search-buttons="searchButtons"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @operation="onOperation"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #oper="scope">
        <operation :row="scope.row" :col="scope.item" @opertion-click="cellOperation" />
      </template>
      <template #portrait="scope">
        <div class="image-preview-box">
          <el-image :src="scope.row.portrait" lazy :preview-teleported="true" fit="cover" :preview-src-list="[scope.row.portrait]" class="image-preview">
            <template #error>
              <div class="image-slot">
                <img src="@/assets/image/default-avatar.png">
              </div>
            </template>
          </el-image>
        </div>
      </template>
    </d-table-promote>
  </page-container>
  <add-archives
    v-if="showDialog"
    :show-dialog="showDialog"
    :dialog-type="dialogType"
    :archives-data="archivesData"
    :selete-nation-data="seleteNationData"
    :past-history-lsit="pastHistoryLsit"
    :select-team-lsit="selectTeamLsit"
    :id-reader="IDReader"
    @close="onClose"
  />
  <div v-if="showInsertDialog">
    <insert :show-dialog="showInsertDialog" :select-team-lsit="selectTeamLsit" :selete-nation-data="seleteNationData" @close="onInsertClose()" />
  </div>
</template>
<style scoped lang="less">
.image-preview-box {
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-preview {
  width: 40px;
  height: 50px;
  img {
    width: 40px;
    height: 50px;
  }
}
:deep(.template-download-btn) {
  text-decoration: underline;
  &:hover {
    color: var(--theme-color-light-3);
  }
}
:deep(.import-btn) {
  color: var(--theme-color);
  border-color: var(--theme-color);
  background-color: var(--theme-color-light-7);
}
</style>
